package cn.turing.firecontrol.admin.rest;

import cn.turing.firecontrol.admin.biz.UserBiz;
import cn.turing.firecontrol.admin.entity.User;
import cn.turing.firecontrol.admin.utils.GitheeProvider;
import cn.turing.firecontrol.admin.utils.HttpUtil;
import cn.turing.firecontrol.admin.vo.AccessTokenDTO;
import cn.turing.firecontrol.admin.vo.GiteeUser;
import cn.turing.firecontrol.common.rest.BaseController;
import com.thoughtworks.xstream.core.util.Base64Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AuthorizeController extends BaseController<UserBiz, User,String> {
    @Autowired
    private AccessTokenDTO accessTokenDTO;
    @Autowired
    private GitheeProvider githeeProvider;


    @GetMapping("/callback")
    public void callback(@RequestParam(name = "code") String code,
                           @RequestParam(name = "state") String state, HttpServletResponse response,HttpServletRequest request) throws IOException {

        accessTokenDTO.setClient_id("42c92cf89d6766edbd7e9ca2bb63703de524dc4497d6cdf388c1acb588be8a60");
        accessTokenDTO.setClient_secret("1f12cb51c85f6f155fd7f20383ccec3c516794b134de8c43e12abfec660713a3");
        accessTokenDTO.setRedirect_uri("http://127.0.0.1:9527/#/login");
        accessTokenDTO.setCode(code);
        accessTokenDTO.setState(state);
        String token = githeeProvider.getAccessToken(accessTokenDTO);
        System.err.println(token);
        GiteeUser giteeUser = githeeProvider.getGiteeUser(token);
        System.out.println("id  :"+giteeUser.getId());
        System.out.println("name  :"+giteeUser.getName());
        System.out.println("bio  :"+giteeUser.getBio());
        String url = "https://gitee.com/api/v5/user";
        String userInfo = HttpUtil.get(url,token);
        String password="";
    try {
        Base64Encoder encoder = new Base64Encoder();
        String encode1 = encoder.encode("123456".getBytes());
        password = encoder.encode((encode1 + "LJ7FXK5").getBytes());


        baseBiz.addUser(giteeUser.getLogin(),giteeUser.getName(),"15511317351",password,null);
    }catch (Exception e){
    e.printStackTrace();
    }finally {
        response.sendRedirect("http://127.0.0.1:9527/#/login?name=admin"+"&password=Turing2018&code=qwer");
    }





//        response.sendRedirect("http://127.0.0.1:9527/#/gailan/overView");


    }
}
